package util

import (
	"encoding/json"
	"strconv"
	"time"
)

type Result struct {
	start      int64
	err        error
	code       int
	ResultCode string              `json:"resultCode"`
	Desc       string              `json:"desc,omitempty"`
	Title      map[string]string   `json:"title,omitempty"`
	Content    []map[string]string `json:"content,omitempty"`
	Summary    map[string]string   `json:"summary,omitempty"`
}

func NewResult() *Result {
	return &Result{start: time.Now().UnixNano()}
}

func (r *Result) PostFinish() *Result {
	cost := int((time.Now().UnixNano() - r.start) / 1000 / 1000)
	r.Desc = "cost " + strconv.Itoa(cost) + "ms"
	return r
}

func (r *Result) QueryFinish() *Result {
	cost := int((time.Now().UnixNano() - r.start) / 1000 / 1000)
	r.Desc = "cost " + strconv.Itoa(cost) + "ms"
	r.Summary = make(map[string]string)
	r.Summary["record count"] = strconv.Itoa(len(r.Content))
	r.ResultCode = strconv.Itoa(r.code)
	if r.Content == nil {
		r.Content = []map[string]string{}
	}
	if r.Title == nil {
		r.Title = make(map[string]string)
	}
	return r
}

func (r *Result) GetError() error {
	return r.err
}

func (r *Result) WithError(err error) *Result {
	r.err = err
	return r
}

func (r *Result) WithValue(value []map[string]string) *Result {
	r.Content = value
	return r
}

func (r *Result) GetCode() int {
	return r.code
}

func (r *Result) WithCode(code int) *Result {
	r.code = code
	return r
}

func (r *Result) Bytes() []byte {
	b, _ := json.Marshal(r)
	return b
}

func (r *Result) String() (ret string) {
	b, _ := json.Marshal(r)
	ret = string(b)
	return
}
